﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;

namespace InterlockStudy
{
    class Program
    {
        static void Main(string[] args)
        {
            var queue = new RingBuffer<int>(20);
            var results = new ConcurrentBag<int>();

            var tasks = new Task[8];

            for (int i = 0; i < 4; i++)
            {
                tasks[i] = Task.Factory.StartNew(() =>
                {
                    for (var j = 0; j < 400000; j++)
                    {
                        queue.EnQueue(j);
                    }
                });
            }

            for (int i = 0; i < 4; i++)
            {
                tasks[4 + i] = Task.Factory.StartNew(() =>
                {
                    for (var j = 0; j < 400000; j++)
                    {
                        results.Add(queue.DeQueue());
                    }
                });
            }

            Task.WaitAll(tasks);

            Console.WriteLine(results.Count);

            Console.ReadLine();
        }
    }
}
